package main.tping.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;

public class SocketNIO {

    public static void main(String[] args) throws Exception {

        LinkedList<SocketChannel> linked = new LinkedList<>();

        ServerSocketChannel ss = ServerSocketChannel.open();
        ss.bind(new InetSocketAddress(8089));
        ss.configureBlocking(false);  // 非阻塞的

        // 循环接收
        for (;;){
            Thread.sleep(1000);
            SocketChannel channel = ss.accept();
            if( channel == null ){
                System.out.println("暂无客户端连接....");
                continue;
            }else{
                channel.configureBlocking(false); // 非阻塞
                int port = channel.socket().getPort();
                linked.add(channel);

                System.out.printf("端口：%s, 客户端连接成功....\n", port);
            }

            ByteBuffer buffer = ByteBuffer.allocateDirect(4 * 1024);

            for ( SocketChannel socketChannel : linked ){
                int i = socketChannel.read(buffer);

                if( i > 0 ){ // 读取到数据
                    buffer.flip();  // 指针颠倒
                    byte[] bytes = new byte[buffer.limit()];
                    buffer.get(bytes);

                    String str = new String(bytes);
                    System.out.printf("读取到的内容：%s", str);
                }
            }
        }

    }
}
